#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019, Niklas Hauser
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

def init(module):
    module.name = ":platform:fault"
    module.description = FileReader("module.md")

def prepare(module, options):
    if not options[":target"].has_driver("core:cortex-m*"):
        return False

    module.add_option(
        EnumerationOption(
            name="report_level",
            description=descr_report_level,
            enumeration=["core", "core+stack", "core+stack+data"],
            default="core+stack+data"))

    module.depends(":crashcatcher", ":cmsis:device", ":architecture:build_id")

    return True

def build(env):
    env.outbasepath = "modm/src/modm/platform/fault"
    env.template("crashcatcher_regions.c.in")
    env.copy(".", ignore=env.ignore_files("*regions.c.in"))


descr_report_level = """# Fault Report Level

This module will try to store as much data as is available in the heap and any
leftover data will be discarded. This means the application may not have any
heap available after a reboot.

You can control how much data is generated by choosing the right report level:

- core: Just dumps the core registers, which describe where the fault occurred
        and why. This is usually less than 250 Bytes.
- stack: Dumps the main stack memory. This will get you a full backtrace, but
         may take a few kB of space.
- data: Dumps all memory sections containing static data: `.data`, `.fastdata`,
        `.bss`. This allows you to see data that isn't related to your current
        fault location, however, this can take several tens of kB of data.

It is strongly recommended to choose the report level that generates less data
than you heap size. The `scons size` output displays this very prominently,
if the Data size is smaller than your Heap size, you're good to use the
`core+stack+data` setting:

```
Data:      5.2 KiB (26.0% used) = 2285 B static (11.2%) + 3040 B stack (14.8%)
(.bss + .data + .fastdata + .noinit + .stack)

Heap:     14.8 KiB (74.0% available)
(.heap1)
```

If Heap is smaller than the Data, you may need to switch to using only the
`core+stack` setting:

```
Data:     11.2 KiB (56.0% used) = 8429 B static (41.2%) + 3040 B stack (14.8%)
(.bss + .data + .fastdata + .noinit + .stack)

Heap:      8.8 KiB (44.0% available)
(.heap1)
```
"""
